﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using WC = System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace QXBook.Utils
{
    /// <summary>
    /// 调用例子
    /// private static string normalPath = ConfigurationSettings.AppSettings["Normal"];   //普通图片路径
    /// private static string smallPath = ConfigurationSettings.AppSettings["Small"];        //缩略图片路径
    /// private FileUploadHelper fileUpload = new FileUploadHelper();
    /// fileUpload.FileUpload = FileUpload1;
    /// fileUpload.SetFile(); //设置文件信息
    /// 保存缩略图到small中
    /// fileUpload.FileCompressPath = smallPath;
    /// flagSmall = fileUpload.CompressImage(218,203,"Cut");
    /// 保存图片到normal中
    /// fileUpload .FilePath=normalPath;
    /// flagNormal = fileUpload.SaveFile();
    /// if(fileUpload.DeleteFile() > 0 )
    /// {
    ///     ShowMessage("删除成功！");
    /// }
    /// else
    /// {
    ///     ShowMessage("删除失败！");
    /// }
    /// </summary>
    public class FileUploadHelper 
    {
        #region 类变量成员
        private string fileName;              //文件原名称
        private string fileNameFull;        //文件全名称
        private string fileNameTime;        //文件修改后名称
        private string fileType;            //文件类型
        private string filePath;            //获取或设置文件存放路径
        private string fileCompressPath;    //当文件为图片类型时获取或设置缩略图存放路径

        private static HttpPostedFile _postedFile;
        #endregion

        #region 类属性成员
        //文件原名称
        public string FileName
        {
            get
            {
                return fileName;
            }
        }

        //文件全名称
        public string FileNameFull
        {
            get
            {
                return fileNameFull;
            }
            set
            {
                fileNameFull = value;
            }
        }

        //文件修改后名称
        public string FileNameTime
        {
            get
            {
                return fileNameTime;
            }
            set
            {
                fileNameTime = value;
            }
        }

        //文件类型
        public string FileType
        {
            get
            {
                return fileType.ToLower();
            }
        }

        //获取或设置文件存放路径
        public string FilePath
        {
            set
            {
                filePath = value;
            }
            get
            {
                return filePath;
            }
        }
        //当文件为图片类型时获取或设置缩略图存放路径
        public string FileCompressPath
        {
            set
            {
                fileCompressPath = value;
            }
            get
            {
                return fileCompressPath;
            }
        }

        //上传文件
        public HttpPostedFile PostedFile
        {
            set
            {
                _postedFile = value;
            }
        }

        public string RefNormalFilePath { get; set; }
        public string RefSmallFilePath { get; set; }

        #endregion

        #region 类构造函数（重载）
        /// <summary>
        /// 无参构造函数
        /// </summary>
        public FileUploadHelper()
        {
        }

        /// <summary>
        /// 有参构造函数
        /// </summary>
        /// <param name="fileUpload">上传文件</param>
        public FileUploadHelper(HttpPostedFile postedFile)
        {
            _postedFile = postedFile;
        }
        #endregion

        #region 设置上传文件属性
        /// <summary>
        /// public int SetFile()
        /// 设置上传文件属性
        /// </summary>
        /// <returns>成功返回1，失败返回-1</returns>
        public int SetFile()
        {
            int flag = -1;
            try
            {
                //文件原名称
                fileName = _postedFile.FileName;

                int index = fileName.LastIndexOf(".");

                string time = DateTime.Now.ToString().Replace("-","").Replace(":","").Replace(" ","");

                //文件全名称
                fileNameFull = _postedFile.FileName;

                //文件修改后名称
                fileNameTime = fileName.Replace(fileName.Substring(0,index),time);

                //文件类型
                fileType = fileName.Substring(index + 1);

                flag = 1;
            }
            catch(Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
            }
            return flag;
        }
        #endregion

        #region 保存上传文件
        /// <summary>
        /// public int SaveFile()
        /// 保存上传文件
        /// </summary>
        /// <returns>成功返回1，失败返回-1</returns>
        public int SaveFile()
        {
            int flag = -1;
            try
            {
                _postedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath + fileNameTime));
                RefNormalFilePath = filePath + fileNameTime;
                flag = 1;
            }
            catch(Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
            }
            return flag;
        }
        #endregion

        #region 当为图片类型时生成缩略图并保存
        /// <summary>
        /// public int MakeCompressImage(int with,int height,string mode)
        /// 当为图片类型时生成缩略图并保存
        /// </summary>
        /// <param name="with"></param>
        /// <param name="height"></param>
        /// <param name="mode">
        /// "W": //指定宽，高按比例 
        /// "H": //指定高，宽按比例
        /// "Cut"://指定高宽裁减</param>
        public int CompressImage(int with,int height,string mode)
        {
            
            int flag = -1;

            int currentWith = with;               //新图片的宽度
            int currentHeight = height;           //新图片的高度

            //获取原图片变量
            System.Drawing.Image origImag = null;

            //新建一个bmp图片
            System.Drawing.Image bitMap=null;

            //新建一个画板
            System.Drawing.Graphics grap = null;

            int x = 0;              //原图片开始位置（x） 
            int y = 0;              //原图片开始位置（y） 
            int origWith;           //原图片的宽度
            int origHeight;         //原图片的高度

            try
            {
                origImag = System.Drawing.Image.FromStream(_postedFile.InputStream);

                origWith = origImag.Width;
                origHeight = origImag.Height;

                switch(mode.ToUpper())
                {
                    case "W":
                        currentHeight = origImag.Height * with / origImag.Width;
                        break;
                    case "H":
                        currentWith = origImag.Width * height / origImag.Height;
                        break;
                    case "CUT":
                        if((double)origImag.Width / (double)origImag.Height > (double)with / (double)height)
                        {
                            origHeight = origImag.Height;
                            origWith = origImag.Height * with / height;

                            y = 0;
                            x = (origImag.Width - origWith) / 2;
                        }
                        else
                        {
                            origWith = origImag.Width;
                            origHeight = origImag.Width * height / with;

                            x = 0;
                            y = (origImag.Height - origHeight) / 2;
                        }
                        break;
                    default:
                        break;
                }

                //新建一个bmp图片
                bitMap = new System.Drawing.Bitmap(currentWith,currentHeight);

                //新建一个画板
                grap = System.Drawing.Graphics.FromImage(bitMap);

                //设置高质量插值法
                grap.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                //设置高质量,低速度呈现平滑程度
                grap.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //清空画布并以透明背景色填充
                grap.Clear(Color.Transparent);

                //在指定位置并且按指定大小绘制原图片的指定部分
                grap.DrawImage(origImag,new Rectangle(0,0,currentWith,currentHeight),new Rectangle(x,y,origWith,origHeight),GraphicsUnit.Pixel);

                string dirpath = (fileCompressPath + fileNameTime).Replace("." + fileType, "");
                if (!Directory.Exists(dirpath))
                    Directory.CreateDirectory(dirpath);

                //保存图片
                bitMap.Save(HttpContext.Current.Server.MapPath(fileCompressPath + fileNameTime),System.Drawing.Imaging.ImageFormat.Jpeg);

                RefSmallFilePath = fileCompressPath + fileNameTime;
                flag = 1;
            }
            catch(Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                origImag.Dispose();
                bitMap.Dispose();
                grap.Dispose();
            }
            return flag;
        }
        #endregion

        #region 删除文件，成功返回1，失败返回-1
        /// <summary>
        /// public int DeleteFile()
        /// 删除文件，成功返回1，失败返回-1
        /// </summary>
        /// <returns>成功返回1，失败返回-1</returns>
        public int DeleteFile()
        {
            int flag = -1;
            try
            {
                //删除原文件
                System.IO.File.Delete(HttpContext.Current.Server.MapPath(filePath + fileNameTime));

                //当为图片类型且有缩略图时删除缩略图
                System.IO.File.Delete(HttpContext.Current.Server.MapPath(fileCompressPath + fileNameTime));
                flag = 1;
            }
            catch(Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
            }
            return flag;
        }
        #endregion
    }


    public class ImageClass
    {
        public Image ResourceImage;
        private int ImageWidth;
        private int ImageHeight;

        public string ErrMessage;

        /// 
        /// 类的构造函数
        /// 
        /// 图片文件的全路径名称
        public ImageClass(string ImageFileName)
        {
            ResourceImage = Image.FromFile(ImageFileName);
            ErrMessage = "";
        }

        public bool ThumbnailCallback()
        {
            return false;
        }

        /// 
        /// 生成缩略图重载方法1，返回缩略图的Image对象
        /// 
        /// 缩略图的宽度
        /// 缩略图的高度
        /// 缩略图的Image对象
        public Image GetReducedImage(int Width, int Height)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);

                return ReducedImage;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return null;
            }
        }

        /// 
        /// 生成缩略图重载方法2，将缩略图文件保存到指定的路径
        /// 
        /// 缩略图的宽度
        /// 缩略图的高度
        /// 缩略图保存的全文件名，(带路径)，参数格式：D:/Images/filename.jpg
        /// 成功返回true，否则返回false
        public bool GetReducedImage(int Width, int Height, string targetFilePath)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
                ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);

                ReducedImage.Dispose();

                return true;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return false;
            }
        }

        /// 
        /// 生成缩略图重载方法3，返回缩略图的Image对象
        /// 
        /// 缩略图的宽度百分比 如：需要百分之80，就填0.8  
        /// 缩略图的Image对象
        public Image GetReducedImage(double Percent)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ImageWidth = Convert.ToInt32(ResourceImage.Width * Percent);
                ImageHeight = Convert.ToInt32(ResourceImage.Width * Percent);

                ReducedImage = ResourceImage.GetThumbnailImage(ImageWidth, ImageHeight, callb, IntPtr.Zero);

                return ReducedImage;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return null;
            }
        }

        /// 
        /// 生成缩略图重载方法4，返回缩略图的Image对象
        /// 
        /// 缩略图的宽度百分比 如：需要百分之80，就填0.8  
        /// 缩略图保存的全文件名，(带路径)，参数格式：D:/Images/filename.jpg
        /// 成功返回true,否则返回false
        public bool GetReducedImage(double Percent, string targetFilePath)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ImageWidth = Convert.ToInt32(ResourceImage.Width * Percent);
                ImageHeight = Convert.ToInt32(ResourceImage.Width * Percent);

                ReducedImage = ResourceImage.GetThumbnailImage(ImageWidth, ImageHeight, callb, IntPtr.Zero);

                ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);

                ReducedImage.Dispose();

                return true;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return false;
            }
        }
    }
}
